<template>
  <div class="app-container layout-container">
    <Breadcrumb />
    <div class="container">
      <div class="side">
        <div class="app-container">
          <CustomTitle title="数据字典" />
        </div>
        <div class="list">
          <div
            :class="{ line: true, active: active.dictName == item.dictName }"
            v-for="item in dictList"
            :key="item.dictId"
            @click="changeDict(item)"
          >
            <span>{{ item.dictName }}</span>
          </div>
          <div :class="{ line: true, active: active.dictName == 'pay_type' }" @click="getPayType({ dictName: 'pay_type' })">
            <span>支付方式</span>
          </div>
        </div>
      </div>
      <div class="table app-container">
        <div class="head">
          <a-button type="primary" @click="showModal('')">
            <template #icon>
              <icon-plus />
            </template>
            新建
          </a-button>
        </div>
        <a-table
          :columns="active.dictName == 'pay_type' ? payColunms : dynamicColmuns"
          :data="active.list"
          :pagination="false"
          :scroll="{ y: '80vh' }"
          sticky-header
          stripe
        >
          <template #status="{ record }">
            <a-tag v-if="record.isSystem == 0" color="arcoblue">系统内置-启用</a-tag>
            <a-switch v-else v-model="record.status" unchecked-value="0" checked-value="1" @change="changeStatus(record)" />
          </template>
          <template #operate="{ record }">
            <template v-if="Number(record.isSystem) != 0">
              <a-button type="text" size="mini" @click="showModal(record)">编辑</a-button>
              <a-button type="text" size="mini" @click="delBefore(record)">删除</a-button>
            </template>
            <span v-else>--</span>
          </template>
        </a-table>
      </div>
    </div>
    <a-modal v-model:visible="addVisible" hide-title simple width="470" @before-ok="verify" @ok="handleAddOk" @close="close">
      <div class="model-content">
        <CustomTitle :title="(isNew ? '新增' : '编辑') + '字典项'" />
        <a-form :model="form" auto-label-width ref="formRef">
          <a-form-item
            v-if="active.isDepend == '1'"
            :label="active.dependName"
            field="dictValue"
            :rules="{ required: true, message: '请选择' }"
          >
            <a-select placeholder="请选择" v-model="form.dictValue">
              <a-option v-for="item in source" :key="item.dictValue" :value="item.dictLabel" :label="item.dictLabel" />
            </a-select>
          </a-form-item>
          <a-form-item
            label="名称"
            :field="active.dictName == 'pay_type' ? 'dictName' : 'dictLabel'"
            :rules="[
              { required: true, message: '请输入' },
              { match: /^(?!\s*$).+$/, message: '请输入' },
              { maxLength: 20, message: '长度不能超过20个字符' }
            ]"
          >
            <a-input placeholder="请输入" v-model="form[active.dictName == 'pay_type' ? 'dictName' : 'dictLabel']" />
          </a-form-item>
          <a-form-item label="排序号" field="orderNum" :rules="{ match: /^\d+$/, message: '请输入正整数' }">
            <a-input-number v-model="form.orderNum" :min="1" />
          </a-form-item>
          <a-form-item label="是否启用" field="status" :rules="{ required: true, message: '请选择' }">
            <a-switch v-model="form.status" unchecked-value="0" checked-value="1" />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <a-modal v-model:visible="delVisible" hide-title simple width="380" @ok="handleDel">
      <div class="del-text">确定要删除数据字典项吗？</div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import Breadcrumb from "@/components/Breadcrumb/index.vue";
import {
  getDictList,
  getDict,
  getSysDict,
  delDict,
  updateDict,
  getPaymentList,
  addPayment,
  editPayment
} from "@/apis/tenantDict";
import { columns, payColunms } from "./config";
import type { DictList, DictItem } from "@/apis/tenantDict/type";
import { Message } from "@arco-design/web-vue";

const active = ref<any>({});
const isNew = ref(true);
/**
 * 弹窗
 */
const addVisible = ref(false);
/**
 * 删除弹窗
 */
const delVisible = ref(false);
const form = ref<any>({
  orderNum: 1,
  status: "1"
});
const dictList = ref<DictList[]>([]);
/**
 * 显示弹窗
 * @param item 编辑弹窗时，回显的数据
 */
const showModal = (item: any) => {
  if (item) {
    form.value = { ...item };
    isNew.value = false;
  } else {
    isNew.value = true;
  }
  addVisible.value = true;
};
const formRef = ref(null);
/**
 * 验证表单
 */
const verify = (): Promise<boolean> => {
  return new Promise(resolve => {
    (formRef as any).value.validate((error: any) => {
      resolve(error == void 0);
    });
  });
};
const dynamicColmuns = computed(() => {
  if (active.value.isDepend == 1) {
    const col = JSON.parse(JSON.stringify(columns));
    col.splice(1, 0, { title: active.value.dependName, dataIndex: "dictValue" });
    return col;
  } else {
    return columns;
  }
});
/**
 * 切换zidian
 */
const changeDict = (item: any) => {
  active.value = { ...item };
  source.value = [];
  getSourcelist();
};

const getPayList = async () => {
  const res = await getPaymentList();
  active.value.list = res.data.map((v: any) => ({ ...v, status: v.status + "" }));
};
const getPayType = (item: any) => {
  active.value = { ...item };
  getPayList();
};
const source = ref<any[]>([]);
const getSourcelist = async () => {
  //如果依赖第三方
  if (active.value.isDepend) {
    if (active.value.dependType == 1) {
      // 查系统
      const res = await getSysDict(active.value.dependVal);
      source.value = res.data;
    } else if (active.value.dependType == 2) {
      // 查非系统
      const res = await getDict(active.value.dependVal);
      source.value = res.data;
    }
  }
};
const delItem = ref({});
/**
 * 初始化
 */
const init = async () => {
  const { data } = await getDictList();
  const list = data || [];
  if (active.value.dictId) {
    active.value = list.filter((v: any) => v.dictId == active.value.dictId)[0];
  } else {
    active.value = list?.[0] || {};
  }
  dictList.value = list;
  getSourcelist();
};
/**
 * 确认新增/修改
 */
const handleAddOk = async () => {
  let current = [];
  let isRepeat = false;
  if (active.value.dictName != "pay_type") {
    current = form.value.dictCode
      ? active.value.list.filter((v: DictItem) => v.dictCode != form.value.dictCode)
      : active.value.list;
    isRepeat = current.some((v: any) => {
      return v.dictValue == form.value.dictValue && v.dictLabel == form.value.dictLabel;
    });
  }
  if (isRepeat) {
    Message.error("字典项已存在");
  } else {
    if (active.value.dictName == "pay_type") {
      await addPayment({ ...form.value, dictType: "pay_type", status: Number(form.value.status) });
      getPayList();
      Message.success("操作成功");
    } else {
      await updateDict({ ...form.value, dictType: active.value.dictType });
      Message.success("操作成功");
      init();
    }
  }
};
/**
 * 改变状态
 */
const changeStatus = async (item: any) => {
  if (active.value.dictName == "pay_type") {
    await editPayment({ ...item, dictType: "pay_type", status: Number(item.status) });
    getPayList();
    Message.success("操作成功");
  } else {
    form.value = { ...item };
    await updateDict({ ...form.value, dictType: active.value.dictType });
    Message.success("操作成功");
    init();
  }
};
/**
 * 删除前
 * @param item 删除项
 */
const delBefore = (item: any) => {
  delItem.value = item;
  delVisible.value = true;
};
/**
 * 确认删除
 */
const handleDel = async () => {
  await delDict((delItem as any).value.dictCode);
  Message.success("删除成功");
  init();
};
const close = () => {
  (formRef as any).value.resetFields();
  form.value = {
    dictValue: "",
    dictLabel: "",
    orderNum: 1,
    status: "1"
  };
};
onMounted(() => {
  init();
});
</script>

<style scoped lang="scss">
@import "index";
:deep(.arco-table-header) th {
  background-color: #f2f6fc !important;
}
:deep(.arco-table-body) tr:nth-child(2n) td {
  background-color: #f5f7fa !important;
}
</style>
